package com.grom.dao;

import java.util.List;

import com.dispacher.config.GlobalConfig;
import com.grom.po.BrandVisitHistory;
import com.grom.po.ContactInfo;
import com.grom.po.Customer;
import com.grom.util.Constants;
import com.grom.util.IDCreator;
import com.holder.DBContextHolder;
import com.holder.DBUTil;

class CustomerDaoImpl implements CustomerDao {

	int pageSize = Integer.valueOf(GlobalConfig
			.getProperty(Constants.KEY_PAGE_SIZE));

	public void save(Customer customer, List<ContactInfo> conList,List<BrandVisitHistory> historyList) {
		customer.setID(IDCreator.getSingleId());
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		DBUTil.save(customer);
		if (conList == null || conList.size() == 0) {
			return;
		}
		for (ContactInfo info : conList) {
			if (info.getID() == null) {
				info.setID(IDCreator.getSingleId());
			}
			info.setRelatedId(customer.getID());
			DBUTil.save(info);
		}
		for (BrandVisitHistory his : historyList) {
			his.setBrandId(customer.getID());
			DBUTil.save(his);
		}
	}

	public void delete(Customer customer) {
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		DBUTil.delete(customer);
	}

	public void update(Customer customer, List<ContactInfo> conList,List<BrandVisitHistory> historyList) {
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		DBUTil.update(customer);
		String sql = "delete from contactinfo where relatedId ='"
				+ customer.getID() + "'";
		DBUTil.update(sql);
		if (conList == null || conList.size() == 0) {
			return;
		}
		for (ContactInfo info : conList) {
			info.setRelatedId(customer.getID());
			DBUTil.save(info);
		}
		sql = "delete from brandvisithistory where brandid ='" + customer.getID() + "'";
		DBUTil.update(sql);
		if (historyList == null || historyList.size() == 0) {
			return;
		}
		for (BrandVisitHistory his : historyList) {
			his.setBrandId(customer.getID());
			DBUTil.save(his);
		}
	}

	/**
	 * 修改为只能取出前面的二十条
	 */
	public List<Customer> getAllCustomer() {
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		String sql = "select * from customer order by id limit " + pageSize;
		List<Customer> result = DBUTil.getResult(sql, Customer.class);
		return result;
	}

	public Customer getCustomerById(String ID) {
		String sql = "select * from customer where id = '" + ID + "'";
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		List<Customer> result = DBUTil.getResult(sql, Customer.class);
		return result.get(0);
	}

	public List<Customer> selectByCondition(String sql) {
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		List<Customer> result = DBUTil.getResult(sql, Customer.class);
		return result;
	}
}
